package cn.jaye.fabric.application;

import cn.jaye.fabric.common.constant.Global;
import cn.jaye.fabric.common.constant.MicroConstant;
import cn.jaye.fabric.domain.model.ApiAccessControl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.jaye.fabric.application.command.ChangeApiPackageCommand;
import cn.jaye.fabric.application.command.CreateApiPackageCommand;
import cn.jaye.fabric.application.command.ListApiPackageCommand;
import cn.jaye.fabric.domain.model.AccessControl;
import cn.jaye.fabric.domain.service.RestTemplateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jaye
 * @create 2018-01-03 9:31
 */
@Service
public class ApiPackageApplicationService {

    @Autowired
    private RestTemplateService restTemplateService;

    @Autowired
    private MicroConstant microConstant;

    @Autowired
    private RestTemplate restTemplate;

    private static final String APIPACKAGR_SERVICE_NAME = "apiauthorize";


    public String listApiPackage(ListApiPackageCommand listApiPackageCommand) {
        String url = microConstant.getApiGatewayAddress() + APIPACKAGR_SERVICE_NAME + "/apipackage/list/condition";
        JSONObject postData = new JSONObject();
        JSONObject pageData = new JSONObject();
        if (listApiPackageCommand.getSizes() != null) {
            pageData.put("sizes", listApiPackageCommand.getSizes());
        }
        if (listApiPackageCommand.getCurrentPage() != null) {
            pageData.put("currentPage", listApiPackageCommand.getCurrentPage());
        }
        postData.put("page", pageData);
        if (StringUtils.isNotBlank(listApiPackageCommand.getCondition())) {
            postData.put("apiPackageId", listApiPackageCommand.getCondition());
            postData.put("apiPackageName", listApiPackageCommand.getCondition());
            postData.put("term", listApiPackageCommand.getCondition());
            postData.put("price", listApiPackageCommand.getCondition());
        }
        JSONObject resultObject = restTemplateService.getUrlResponse(url, postData);
        return JSON.toJSONString(resultObject);
    }

    public String listApiPackageAll() {
        String url = microConstant.getApiGatewayAddress() + APIPACKAGR_SERVICE_NAME + "/apipackage/list";
        JSONObject postData = new JSONObject();
        JSONObject resultObject = restTemplateService.getUrlResponse(url, postData);
        return JSON.toJSONString(resultObject);
    }

    public String getApiPackage(String apiPackageId) {
        String url = microConstant.getApiGatewayAddress() + APIPACKAGR_SERVICE_NAME + "/apipackage/get";
        JSONObject postData = new JSONObject();
        postData.put("apiPackageId", apiPackageId);
        JSONObject resultObject = restTemplateService.getUrlResponse(url, postData);
        return JSON.toJSONString(resultObject);
    }

    public String createApiPackage(CreateApiPackageCommand createApiPackageCommand) {
        String url = microConstant.getApiGatewayAddress() + APIPACKAGR_SERVICE_NAME + "/apipackage/create/v1";
        JSONObject postData = new JSONObject();
        postData.put("apiPackageName", createApiPackageCommand.getApipackageName());
        postData.put("term", createApiPackageCommand.getTerm());
        postData.put("price", createApiPackageCommand.getPrice());
        postData.put("enableState", true);
        postData.put("descriptionDoc", createApiPackageCommand.getDescriptionDoc());
        JSONObject resultObject = restTemplateService.getUrlResponse(url, postData);
        return JSON.toJSONString(resultObject);
    }


    public String test() {
        return "{\"code\":1000,\"data\":{\"deleteFlag\":false,\"createBy\":\"\",\"enableState\":1,\"apis\":[{\"apiId\":\"a7b36fe4dc10447ab70580fcf2bc50c2\",\"apiName\":\"计算接口\",\"createBy\":\"jyuan.li\",\"createTime\":1505459642000,\"deleteFlag\":false,\"description\":\"计算接口\",\"serviceId\":\"s7b36fe4dc10447ab70580fcf2bc50b7\",\"updateBy\":\"\",\"updateTime\":1505459642000,\"url\":\"/calculate/addwithdecrypt\"}],\"createTime\":1505463196000,\"updateBy\":\"\",\"price\":100.0,\"descriptionDoc\":\"www.baidu.com\",\"apiPackageName\":\"测试服务包001\",\"term\":6000,\"updateTime\":null,\"apiPackageId\":\"7e13d5a67f924432b3a0a03d25aebc6e\"},\"msg\":\"success\"}";
    }

    public boolean saveChange(ChangeApiPackageCommand changeApiPackageCommand) {
        String apiPackageId = changeApiPackageCommand.getApiPackageId();
        String[] addApis = changeApiPackageCommand.getAddApis();
        String[] deleteApis = changeApiPackageCommand.getDeleteApis();
        String bindUrl = microConstant.getApiGatewayAddress() + APIPACKAGR_SERVICE_NAME + "/apipackage/apis/bind";
        String removeUrl = microConstant.getApiGatewayAddress() + APIPACKAGR_SERVICE_NAME + "/apipackage/apis/remove";
//        String removeUrl ="http://localhost:8809/apipackage/apis/remove";
        try {
            settingapiPackage(bindUrl, apiPackageId, addApis);
            settingapiPackage(removeUrl, apiPackageId, deleteApis);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    private void settingapiPackage(String url, String apiPackageId, String[] apis) {
        List<AccessControl> accessControlList = new ArrayList<>();
        AccessControl accessControl = new AccessControl();
        accessControl.setAccessTimes(100);
        accessControl.setFrequencyUnit(3);
        accessControlList.add(accessControl);
        if (apis != null && apis.length > 0) {
            List<ApiAccessControl> addApiList = new ArrayList<>();
            for (String apiId : apis) {
                ApiAccessControl apiAccessControl = new ApiAccessControl();
                apiAccessControl.setApiId(apiId);
                apiAccessControl.setAccessControl(accessControlList);
                addApiList.add(apiAccessControl);
            }
            if (addApiList.size() > 0) {
                JSONObject postData = new JSONObject();
                postData.put("apiPackageId", apiPackageId);
                postData.put("apis", addApiList);
                JSONObject resultObject = restTemplateService.getUrlResponse(url, postData);
                if (Global.SUCCESS_FLAG.equals(resultObject.getInteger("code"))) {
                    System.out.println("操作成功");
                } else {
                    System.out.println("操作失败");
                }
            }
        }
    }
}
